using System.Web.Mvc;
using Headspring.Training.Core.Model;
using Headspring.Training.Core.Services;
using Headspring.Training.UI.Filters;
using Headspring.Training.UI.Models;
using MvcContrib;

namespace Headspring.Training.UI.Controllers
{
	[AuthenticationFilter]
	public class SearchController : Controller
	{
		private readonly IEmployeeRepository _employeeRepository;
		private readonly IWorkOrderRepository workOrderRepository;

		public SearchController(IWorkOrderRepository workOrderRepository,
		                        IEmployeeRepository employeeRepository)
		{
			this.workOrderRepository = workOrderRepository;
			_employeeRepository = employeeRepository;
		}

		public ActionResult List(string assignee, string creator, string status)
		{
			Employee selectedCreator = getEmployee(creator);
			Employee selectedAssignee = getEmployee(assignee);
			WorkOrderStatus selectedStatus = getStatus(status);

			populateLists(selectedCreator, selectedAssignee, selectedStatus);

			var specification = new WorkOrderSearchSpecification();
			specification.MatchCreator(selectedCreator);
			specification.MatchAssignee(selectedAssignee);
			specification.MatchStatus(selectedStatus);

			WorkOrder[] orders = workOrderRepository.FindWorkOrders(specification);
			ViewData.Add(orders);
			return View("index");
		}

		private Employee getEmployee(string userName)
		{
			if (string.IsNullOrEmpty(userName))
			{
				return null;
			}

			return _employeeRepository.GetByUserName(userName);
		}

		public ActionResult Index()
		{
			populateLists(null, null, null);
			return View();
		}

		private void populateLists(Employee selectedCreator,
		                           Employee selectedAssignee,
		                           WorkOrderStatus selectedStatus)
		{
			Employee[] allEmployees = _employeeRepository.GetAllEmployeesSorted();
			var creators = new EmployeeOptionalSelectList(allEmployees, selectedCreator);
			var assignees = new EmployeeOptionalSelectList(allEmployees,
			                                               selectedAssignee);

			WorkOrderStatus[] allStatuses = WorkOrderStatus.GetAllItems();
			var statuses = new WorkOrderStatusOptionalSelectList(allStatuses,
			                                                     selectedStatus);

			ViewData.Add("assignees", assignees);
			ViewData.Add("creators", creators);
			ViewData.Add(statuses);
		}

		private WorkOrderStatus getStatus(string status)
		{
			if (string.IsNullOrEmpty(status))
			{
				return null;
			}

			return WorkOrderStatus.FromKey(status);
		}
	}
}